// 全局请求封装
import store from '@/store/index.js'
import config from '@/config/config.js'


export default (url, method, params, showLoading=false) => {
	if(showLoading) {
		uni.showLoading({
			title: '加载中...',
			mask: true
		});
	}
	// 获取本地token
	let loginUser = store.state.user;
	const token = loginUser.token ? loginUser.token : '';
	let header;
	if (method == "post") {
		header = {
			AuthToken: token,
			"content-type": "application/json",
		}
	} else {
		header = {
			AuthToken: token,
		}
	}
	return new Promise((resolve, reject) => {
		uni.request({
			url: config.baseUrl + url,
			method: method,
			header: header,
			data: params,
			success(response) {
				let res = response;
				console.log(res);
				if (res.statusCode == '200' || res.status == '200') {
					if (res.data && res.data.code === 2000) {
						resolve(res.data);
					} else if (res.data && res.data.code === 5004 && url != '/auth/login') {
						uni.showToast({
							icon: 'none',
							position: 'bottom',
							title: '请登录后操作'
						});
						setTimeout(() => {
							uni.navigateTo({
								url: '/pages/me/login/login'
							})
						}, 1000)
					} else {
						reject(res.data);
					}
				} else {
					uni.showToast({
						icon: 'error',
						position: 'bottom',
						title: '请求失败'
					});
					reject(res);
				}
			},
			fail(err) {
				uni.showToast({
					icon: 'error',
					position: 'bottom',
					title: '请求失败'
				});
				reject(res);
			},
			complete() {
				if(showLoading) {
					uni.hideLoading();
				}
			}
		});
	});
	
};